import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/components/button_components/base_light_outline_button.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';
///**
///* @fileName: base_customize_dropdown_multiple_select_dialog
///* @author: hrongyong
///* @date-time: 12/14/21 9:32 AM
///* @email: hrongyong@gmail.com
///* description:
///* <fileName> <author> <date-time> <email> <description>
///* 文件名 作者姓名 创建时间 作者邮箱 文件描述
///*/
class BaseCustomizeDropdownMultipleSelectDialog extends StatefulWidget {
  // 是否启用自定义的"全部",默认开启
  final bool enableCustomAll;

  // 全部选项
  final List<BaseKeyValueModel> optionsList;

  // 已选项目
  final List<BaseKeyValueModel> selectedItem;

  // 选中回调
  final Function(List<BaseKeyValueModel> selectModel) selectCallBack;

  // 预留高度
  final double reservedHeight;

  const BaseCustomizeDropdownMultipleSelectDialog({Key key, @required this.selectCallBack, @required this.reservedHeight, @required this.optionsList, @required this.selectedItem, this.enableCustomAll = true}) : super(key: key);

  @override
  _BaseCustomizeDropdownMultipleSelectDialogState createState() => _BaseCustomizeDropdownMultipleSelectDialogState();
}

class _BaseCustomizeDropdownMultipleSelectDialogState extends State<BaseCustomizeDropdownMultipleSelectDialog> {
  ///标题栏（appbar）
  static double _appbarHeight = AppBar().preferredSize.height;

  // 全部选项
  List<BaseKeyValueModel> _optionsList = [];

  // 已选项目
  List<BaseKeyValueModel> _selectedItem = [];

  /// 系统颜色 黑 Color(0xff333333) 白：Color(0xffffffff) 黑白主题选中颜色为Color(0xFFFF004F)
  Color get systemColor => Theme.of(context).primaryColor == Colors.white || Theme.of(context).primaryColor == Color(0xFF333333) ? Color(0xFFFF004F) : Theme.of(context).primaryColor;


  @override
  void initState() {
    super.initState();
    _optionsList.clear();
    _optionsList.addAll(widget.optionsList);
    _selectedItem.clear();
    _selectedItem.addAll(widget.selectedItem);

    if (widget.enableCustomAll) {
      // 删除原有的"全部"
      _optionsList.removeWhere((element) => element.key == -2 || element.value == "全部" || element.key == "全部");
      // 添加自定义的全部
      _optionsList.insert(0, BaseKeyValueModel(key: '-2', value: '全部'));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: SafeArea(
        child: Column(
          children: [
            SizedBox(height: _appbarHeight + widget.reservedHeight),
            BaseComponentUtils.buildHorizontalDivider(),
            Container(color: Colors.white, constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.7), child: _buildListView()),
            _buildBottomButton(),
            Expanded(child: InkWell(onTap: () => BaseRouterUtil.getInstance().pop(), child: Container(color: Color(0XAA000000)))),
          ],
        ),
      ),
    );
  }

  Widget _buildListView() {
    return ListView.separated(
      shrinkWrap: true,
      itemCount: _optionsList.length,
      itemBuilder: (BuildContext context, int index) => _buildItem(context, _optionsList[index], index),
      separatorBuilder: (BuildContext context, int index) => BaseComponentUtils.buildHorizontalDivider(),
    );
  }

  Widget _buildItem(BuildContext context, BaseKeyValueModel model, int index) {
    int _selectIndex = _selectedItem.indexWhere((element) => element.key == model.key);
    return InkWell(
      onTap: () => _onItemEvent(model, _selectIndex),
      child: Container(
        height: 48,
        padding: EdgeInsets.symmetric(horizontal: 16),
        color: _selectIndex != -1 ? Color(0xFFF8F8F8) : Colors.white,
        child: Row(
          children: [
            Expanded(child: Text(model.value, style: TextStyle(color: _selectIndex != -1 ? systemColor : Color(0xFF333333)))),
            SizedBox(width: 12),
            Container(
              width: 18.0,
              height: 18.0,
              decoration: BoxDecoration(shape: BoxShape.circle, color: _selectIndex != -1 ? systemColor : Colors.white, border: Border.all(color: _selectIndex != -1 ? systemColor : Color(0xFF868686))),
              child: Icon(BaseIconData.x3Checked, size: 12, color: _selectIndex != -1 ? Colors.white : Colors.transparent),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomButton() {
    return Container(
      width: double.infinity,
      color: Color(0xFFF3F3F3),
      child: Row(
        children: [
          Expanded(child: BaseLightOutlineButton(text: "取消", onPressed: _onCancel)),
          SizedBox(width: 12.0),
          Expanded(child: BaseLightOutlineButton(text: "重置", onPressed: _onReset)),
          SizedBox(width: 12.0),
          Expanded(child: BaseLightOutlineButton(text: "确定", onPressed: _onDetermine)),
        ],
      ),
    );
  }

  void _onItemEvent(BaseKeyValueModel model, int selectIndex) {
    if (selectIndex != -1) {
      this._selectedItem.removeAt(selectIndex);
    } else {
      if (widget.enableCustomAll) {
        if (model.value == '全部') {
          this._selectedItem.clear();
        } else {
          int _allIndex = this._selectedItem.indexWhere((element) => element.value == '全部');
          if (_allIndex != -1) this._selectedItem.removeAt(_allIndex);
        }
      }
      this._selectedItem.add(model);
    }

    setState(() {});
  }

  /// 取消
  void _onCancel() {
    BaseRouterUtil.getInstance().pop();
  }

  /// 重置
  void _onReset() {
    this._selectedItem.clear();
    this._selectedItem.addAll(widget.selectedItem);
    setState(() {});
  }

  /// 确定
  void _onDetermine() {
    widget.selectCallBack(this._selectedItem);
    BaseRouterUtil.getInstance().pop();
  }
}
